import os
import sys
import subprocess
import shutil

NDK_PATH = os.environ["NDK_HOME"] if "NDK_HOME" in os.environ else None

GODOT_PROJECT_PATH = "widget-demo"

LIB_NAME = "zwidgets"

def build():
    def parse_args():
        args = sys.argv
        ret = {}
        cur = None
        for arg in args:
            if arg.startswith("--"):
                cur = arg[2:]
                ret[cur] = []
                continue

            if cur != None:
                ret[cur].append(arg)

        return ret

    attrs = parse_args()

    print(attrs)

    release_build = "release" in attrs
    extra_targets = [] if "extra" not in attrs else attrs["extra"]

    cargo_build_cmd = ["cargo", "build"]

    if release_build:
        cargo_build_cmd.append("--release")

    subprocess.Popen(cargo_build_cmd).wait()

    print("Build platform:" + sys.platform)
    build_folder = "release" if release_build else "debug"

    def libsrc(libfile):
        return os.path.join("target", build_folder, libfile)

    def libdst(platform, libfile):
        return os.path.join(GODOT_PROJECT_PATH, "gdextension", LIB_NAME, platform, build_folder, libfile)
    
    if "linux" in sys.platform:
        file = "lib{}.so".format(LIB_NAME)
        shutil.copy(libsrc(file), libdst("linux", file))
    elif "win32" in sys.platform or "cygwin" in sys.platform:
        file = "{}.dll".format(LIB_NAME)
        shutil.copy(libsrc(file), libdst("windows", file))
    elif "darwin" in sys.platform:
        file = "lib{}.dylib".format(LIB_NAME)
        shutil.copy(libsrc(file), libdst("macos", file))
    
    for target in extra_targets:
        
        pass


build()